package com.nondo.rdp.finance.service.impl.course;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.core.common.IPUtil;
import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.finance.common.OrderUtil;
import com.nondo.rdp.finance.common.PayConfig;
import com.nondo.rdp.finance.common.PayDigestUtil;
import com.nondo.rdp.finance.common.XXPayUtil;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.domain.course.CourseBuy;
import com.nondo.rdp.finance.model.RequestPayBean;
import com.nondo.rdp.finance.repository.course.CourseBuyRepository;
import com.nondo.rdp.finance.service.course.CourseBuyService;

@Transactional
@Service
public class CourseBuyServiceImpl implements CourseBuyService {
	
	private static Logger _log = LoggerFactory.getLogger(CourseBuyServiceImpl.class);
	
    @Autowired
    CourseBuyRepository courseBuyRepository;

    @Override
    public CourseBuy findOne(Long id) {
        return this.courseBuyRepository.findOne(id);
    }

    @Override
    public CourseBuy save(CourseBuy courseBuy) {
        return this.courseBuyRepository.save(courseBuy);
    }

    @Override
    public void update(CourseBuy courseBuy) {
        this.courseBuyRepository.save(courseBuy);
    }
    
    @Override
    public void delete(Long id) {
        this.courseBuyRepository.deleteById(id);
    }

    @Override
    public Page<CourseBuy> findAll(Page<CourseBuy> page, Course course) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<CourseBuy> dictPage = courseBuyRepository.findAll((root, query, builder) -> {
        	List<Predicate> predicates = new ArrayList<>();
        	if (course != null) {
        		if(course.getUser() != null){
        			predicates.add(builder.equal(root.get("user").get("id"), course.getUser().getId()));
        		}
	            if (course.getType() != null) {
	                predicates.add(builder.equal(root.get("course").get("type"), course.getType()));
	            }
	            if (course.getStatus() != null) {
        			predicates.add(builder.equal(root.get("status"), course.getStatus()));
	            }
	            if (StringUtils.isNotEmpty(course.getName())) {
	                predicates.add(builder.like(root.get("course").get("name"), "%" + course.getName() + "%"));
	            }
        	}
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
        	
            return builder.and(predicatesArray);
        	
        }, pageRequest);

        return new Page<CourseBuy>(dictPage);
    }

	@Override
	public int getOne(Long cid, Long uid) {
		CourseBuy courseBuy = this.courseBuyRepository.getOne(cid ,uid);
		return (courseBuy != null) ? 1 : 0;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Map order(CourseBuy courseBuy, RequestPayBean payBean) {
		Course course = courseBuy.getCourse();
		User user = courseBuy.getUser();
		String orderNo = OrderUtil.getMchOrderNo(user.getId());
		JSONObject paramMap = new JSONObject();
        paramMap.put("mchId", PayConfig.mchId);                               // 商户ID
        paramMap.put("mchOrderNo", orderNo);     // 商户订单号
        paramMap.put("channelId", payBean.getChannelId());  // 支付渠道
        paramMap.put("amount", (int)(course.getPrice()*100));                                  // 支付金额,单位分
        paramMap.put("currency", PayConfig.cny);                            // 币种, cny-人民币
        paramMap.put("clientIp", IPUtil.getLocalIP());                 // 用户地址,IP或手机号
        paramMap.put("device", PayConfig.device.APP);                              // 设备
        paramMap.put("subject", course.getName());
        paramMap.put("body", PayConfig.app + "-" + course.getName());
        paramMap.put("notifyUrl", PayConfig.notifyUrl);                       // 回调URL
        JSONObject extra = new JSONObject();
        extra.put("productId", course.getId());
        paramMap.put("extra",extra);  // 附加参数

        String reqSign = PayDigestUtil.getSign(paramMap, PayConfig.reqKey);
        paramMap.put("sign", reqSign);                              // 签名
        _log.info("请求支付中心下单接口,请求数据:" + paramMap.toJSONString());
        String result = XXPayUtil.call4Post(PayConfig.createOrderUrl, paramMap.toJSONString());
        _log.info("请求支付中心下单接口,响应数据:" + result);
		Map retMap = JSON.parseObject(result);
        if("SUCCESS".equals(retMap.get("retCode")) && "SUCCESS".equalsIgnoreCase(retMap.get("resCode").toString())) {
            // 验签
            @SuppressWarnings("unchecked")
			String checkSign = PayDigestUtil.getSign(retMap, PayConfig.repKey, "sign", "payParams");
            String retSign = (String) retMap.get("sign");
            if(checkSign.equals(retSign)) {
            	_log.info("=========支付中心下单验签成功=========");
            	courseBuy.setOrderNo(orderNo);
            	courseBuy.setAmount(course.getPrice());
				courseBuy.setStatus(0);
				this.courseBuyRepository.save(courseBuy);
            }else {
            	_log.error("=========支付中心下单验签失败=========");
                return null;
            }
        }
        return retMap;
		
	}

	@Override
	public CourseBuy findByOrderNo(String mchOrderNo) {
		return this.courseBuyRepository.findByOrderNo(mchOrderNo);
	}
}